package com.tinem.platform.service.network.client.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.tinem.platform.module.starter.jpa.entity.network.IpInfo;
import com.tinem.platform.service.network.client.IpInfoClient;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

/**
 * @author fzh
 * @version v1
 * @program: platform
 * @className TengXun
 * @description 通过腾讯获取ip信息
 * @site
 * @company
 * @create 2021-10-27 14:38
 */
@Slf4j
@Service
public class Ip138IpInfoClient implements IpInfoClient {

    //token
    @Value("${ip138.token}")
    String token;
    @Value("${ip138.url}")
    String url;

    @Override
    public IpInfo getLocationByIp(String ip) {
        log.info("api ip138 ip:{}",ip);
        String url = StrUtil.format(this.url,ip,token);
        HttpRequest request = HttpRequest.get(url);
        log.info("api ip138 url:{} X-Source:{}  X-Date:{} Authorization:{}",url);
        String result = request.execute().body();
        log.info("api ip138 res:{}",result);
        JSONObject jsonObject = JSON.parseObject(result);
        if(!"ok".equals(jsonObject.getString("ret"))){
            return null;
        }
        JSONArray data = jsonObject.getJSONArray("data");
        IpInfo ipInfo = new IpInfo();
        ipInfo.setIp(ip);
        ipInfo.setCountry(data.getString(0));
        ipInfo.setProvince(data.getString(1));
        ipInfo.setCity(data.getString(2));
        ipInfo.setIsp(data.getString(4));
        return ipInfo;
    }

}
